<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="所属门店" prop="storeCode">
        <el-select v-model="formData.storeCode" placeholder="请选择门店" @change="showEmployeeList">
          <el-option
            v-for="store in storeList"
            :key="store.code"
            :label="store.name"
            :value="store.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="选择员工" prop="systemUserCode">
        <el-select
          v-model="formData.systemUserCode"
          placeholder="请选择员工"
          reserve-keyword
          filterable
        >
          <el-option
            v-for="storeEmployee in storeEmployeeList"
            :key="storeEmployee.systemUserCode"
            :label="storeEmployee.systemUserName + '-' + storeEmployee.phone"
            :value="storeEmployee.systemUserCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="对外昵称" prop="nickname">
        <el-input v-model="formData.nickname" placeholder="请输入对外昵称" />
      </el-form-item>
      <el-form-item label="门店项目" prop="project">
        <el-select
          v-model="formData.project"
          placeholder="请选择门店项目"
          multiple
          value-key="code"
        >
          <el-option
            v-for="storeProject in storeProjectList"
            :key="storeProject.code"
            :label="storeProject.name"
            :value="storeProject"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="级别" prop="level">
        <el-select v-model="formData.level" placeholder="请选择级别">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.MEIJIA_HAIRDRESSER_LEVEL)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="从业经验">
        <el-button type="primary" @click="experienceAdd">新增从业经验</el-button>
      </el-form-item>
      <el-form-item>
        <el-row
          :gutter="5"
          v-for="(domain, index) in formData.experience"
          :key="domain.key"
          :prop="'domains.' + index + '.value'"
        >
          <el-col :span="8">
            <el-input v-model="domain.organizationName" placeholder="机构名称" />
          </el-col>
          <el-col :span="7">
            <el-date-picker
              style="width: 100%"
              v-model="domain.beginTime"
              type="month"
              placeholder="开始时间"
            />
          </el-col>
          <el-col :span="7">
            <el-date-picker
              style="width: 100%"
              v-model="domain.endTime"
              type="month"
              placeholder="结束时间"
            />
          </el-col>
          <el-col :span="2" @click="experienceDel(index)">
            <el-icon><RemoveFilled /></el-icon>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="是否有推荐人" prop="hasReference">
        <el-radio-group v-model="formData.hasReference" class="ml-4">
          <el-radio :label="true" size="large">是</el-radio>
          <el-radio :label="false" size="large">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="推荐人员工"
        prop="referenceSystemUserCode"
        v-if="showReferenceSystemUserCode"
      >
        <el-select
          v-model="formData.referenceSystemUserCode"
          placeholder="请选择推荐人员工"
          remote
          :remote-method="showStoreEmployeeReferenceList"
          reserve-keyword
          filterable
        >
          <el-option
            v-for="storeEmployeeRef in storeEmployeeReferenceList"
            :key="storeEmployeeRef.systemUserCode"
            :label="storeEmployeeRef.systemUserName + '-' + storeEmployeeRef.phone"
            :value="storeEmployeeRef.systemUserCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否展示" prop="hasShow">
        <el-radio-group v-model="formData.hasShow" class="ml-4">
          <el-radio :label="true" size="large">显示</el-radio>
          <el-radio :label="false" size="large">隐藏</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { RemoveFilled, CirclePlusFilled } from '@element-plus/icons-vue'
import * as StoreEmployeeApi from '@/api/meijia/store/employee'
import * as AgentApi from '@/api/meijia/agent'
import * as AgentEmployeeApi from '@/api/meijia/agent/employee'
import * as StoreApi from '@/api/meijia/store'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import * as ProjectApi from '@/api/meijia/project'
import * as UserDetailApi from '@/api/system/user'
import { tr } from 'node_modules/element-plus/es/locale'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const value1 = ref('')

const defaultTime1 = new Date(2000, 1, 1, 12, 0, 0) // '12:00:00'

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  code: undefined,
  agentCode: undefined,
  storeCode: undefined,
  systemUserCode: undefined,
  nickname: undefined,
  level: undefined,
  hasReference: true,
  referenceSystemUserCode: undefined,
  hasShow: true,
  project: [],
  experience: []
})
const formRules = reactive({
  code: [{ required: true, message: '编号不能为空', trigger: 'blur' }],
  agentCode: [{ required: true, message: '所属区域编号不能为空', trigger: 'blur' }],
  storeCode: [{ required: true, message: '所属门店编号不能为空', trigger: 'blur' }],
  project: [{ required: true, message: '项目不能为空', trigger: 'blur' }],
  systemUserCode: [{ required: true, message: '人员编号不能为空', trigger: 'blur' }],
  nickname: [{ required: true, message: '对外昵称不能为空', trigger: 'blur' }],
  level: [{ required: true, message: '级别不能为空', trigger: 'blur' }],
  hasReference: [{ required: true, message: '是否有推荐人不能为空', trigger: 'blur' }],
  hasShow: [{ required: true, message: '是否展示不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const agentEmployee = ref<AgentEmployeeApi.AgentEmployeeVO>()
const storeList = ref<StoreApi.StoreVO>()
const storeEmployeeList = ref<StoreEmployeeApi.StoreEmployeeVO>()
const storeProjectList = ref<ProjectApi.ProjectVO>()
const showReferenceSystemUserCode = ref(true)
const storeEmployeeReferenceList = ref()
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  showStoreList()
  showStoreProjectList()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await StoreEmployeeApi.getStoreEmployee(id)
      console.log(formData)
      formData.value.experience.forEach((element) => {
        element.beginTime =
          new Date(parseInt(element.beginTime)).toLocaleDateString().replace(/\//g, '-') +
          ' ' +
          new Date(parseInt(element.beginTime)).toTimeString().substr(0, 8)
        element.endTime =
          new Date(parseInt(element.endTime)).toLocaleDateString().replace(/\//g, '-') +
          ' ' +
          new Date(parseInt(element.endTime)).toTimeString().substr(0, 8)
      })
      console.log(formData.value.experience)
      showEmployeeList(formData.value.storeCode)
      if (formData.value.referenceSystemUserName) {
        showStoreEmployeeReferenceList(formData.value.referenceSystemUserName)
      }
    } finally {
      formLoading.value = false
    }
  }
  if (!formData.value.experience || formData.value.experience.length <= 0) {
    formData.value.experience = [
      {
        organizationName: null,
        beginTime: null,
        endTime: null
      }
    ]
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as StoreEmployeeApi.StoreEmployeeVO
    data.experience.forEach((element) => {
      element.beginTime = new Date(element.beginTime).getTime()
      element.endTime = new Date(element.endTime).getTime()
    })
    if (formType.value === 'create') {
      await StoreEmployeeApi.createStoreEmployee(data)
      message.success(t('common.createSuccess'))
    } else {
      await StoreEmployeeApi.updateStoreEmployee(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
//新增从业经验

const experienceAdd = () => {
  console.log(formData)
  formData.value.experience.push({
    organizationName: null,
    beginTime: null,
    endTime: null
  })
}
//删除从业经验

const experienceDel = (index) => {
  console.log(formData)
  formData.value.experience.splice(index, 1)
}
//确定时间
const pickerChange = (e) => {
  console.log(e)
}
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    code: undefined,
    agentCode: undefined,
    storeCode: undefined,
    systemUserCode: undefined,
    nickname: undefined,
    level: undefined,
    hasReference: true,
    referenceSystemUserCode: undefined,
    hasShow: true
  }
  formRef.value?.resetFields()
  storeList.value = []
  storeEmployeeList.value = []
  storeProjectList.value = []
  storeEmployeeReferenceList.value = []
}
const showStoreList = async () => {
  agentEmployee.value = AgentEmployeeApi.agentEmployeeByCurrentUser()
  if (agentEmployee.value.data) {
    storeList.value = await StoreApi.getByAgentCodeContainNull({
      agentCode: agentEmployee.value.agentCode
    })
  } else {
    storeList.value = await StoreApi.getByAgentCodeContainNull()
  }
}
const showEmployeeList = async (storeCode) => {
  storeEmployeeList.value = await StoreEmployeeApi.getBindableOrdinaryEmployeeList({
    storeCode: storeCode
  })
}
const showStoreProjectList = async () => {
  storeProjectList.value = await ProjectApi.getStoreProject()
}
const showStoreEmployeeReferenceList = async (name: String) => {
  if (name) {
    storeEmployeeReferenceList.value = await UserDetailApi.getReferenceUserDetailByUserName(name)
  }
}
watch(
  () => formData.value.hasReference,
  (New, Old) => {
    if (New == false) {
      formData.value.referenceSystemUserCode = undefined
      showReferenceSystemUserCode.value = false
    } else {
      showReferenceSystemUserCode.value = true
    }
  }
)
</script>
<style scoped>
.el-select {
  width: 100%;
}
</style>
